package com.aps.advice;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.aps.entity.ApsExeption;
import com.aps.entity.ExceptionEntity;
import com.aps.entity.ResultEntity;
import com.aps.entity.eunm.ResultType;

/**
 * @author liaoguangan
 * @description <>
 * @date 2018/4/6 9:26
 */
@ControllerAdvice
public class ApiExceptionAdvice {

    private String method = "";
    private String clazz = "";
    private String exception = "";
    private String message = "";
    private String operation = "";

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public ResultEntity handleIOException(Exception ex) {
        ex.printStackTrace();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
        Boolean isMobile = "mobile".equals(request.getHeader("device-type"));
        setExceptionInfo(ex);

        if (isMobile) {
            //do somthing
        } else {
            //do somthing
        }

        ExceptionEntity be = new ExceptionEntity(true, message, operation, exception, method,
                clazz);

        ResultEntity b = new ResultEntity(false, ResultType.SERVER_ERROR, be);
        if (ex instanceof ApsExeption) {
            b = new ResultEntity(false, ((ApsExeption) ex).getResultType(), be);
        }

        return b;
    }

    private void setExceptionInfo(Exception ex) {
        StackTraceElement[] st = ex.getStackTrace();
        this.method = st[0].getMethodName();
        this.clazz = st[0].getClassName().toString();
        this.exception = ex.toString();
        this.message = ex.getMessage();
    }
}
